import { ref, reactive } from '@vue/runtime-core'
import { ElMessage } from 'element-plus'
import * as systemApi from '../api/system'
import type { SystemSettings } from '../api/system'

export const useSystemSettings = () => {
  // 系统设置相关的响应式数据
  const loading = ref(false)
  const saving = ref(false)
  
  // 设置数据
  const settings = reactive<SystemSettings>({})
  
  // 基础设置
  const basicSettings = reactive({
    systemInfo: {
      name: '小采灵犀智能对账系统',
      description: '基于AI技术的智能对账平台',
      version: 'v1.0.0',
      copyright: '© 2023 小采科技有限公司'
    },
    systemBehavior: {
      autoSave: true,
      autoRefresh: false,
      refreshInterval: 60,
      theme: 'light'
    }
  })
  
  // 安全设置
  const securitySettings = reactive({
    passwordPolicy: {
      minLength: 8,
      requireNumber: true,
      requireSpecialChar: true,
      requireUppercase: true,
      expireDays: 90
    },
    loginSecurity: {
      maxAttempts: 5,
      lockoutDuration: 30,
      sessionTimeout: 120
    }
  })
  
  // 网络设置
  const networkSettings = reactive({
    api: {
      timeout: 10000,
      retryCount: 3,
      baseUrl: 'https://api.example.com'
    },
    proxy: {
      enabled: false,
      host: '',
      port: 8080
    }
  })
  
  // 加载系统设置
  const loadSettings = async () => {
    loading.value = true
    try {
      const response = await systemApi.getSystemSettings()
      
      if (response.data) {
        Object.assign(settings, response.data)
        // 这里可以根据API返回的数据更新设置
      }
    } catch (error: any) {
      console.error('加载系统设置失败:', error)
      ElMessage.error('加载系统设置失败: ' + (error.message || '未知错误'))
    } finally {
      loading.value = false
    }
  }
  
  // 保存系统设置
  const saveSettings = async () => {
    try {
      saving.value = true
      
      // 收集所有设置数据，转换为字符串类型
      const settingsData: Record<string, string> = {
        // 系统信息
        'system.name': basicSettings.systemInfo.name,
        'system.description': basicSettings.systemInfo.description,
        'system.version': basicSettings.systemInfo.version,
        'system.copyright': basicSettings.systemInfo.copyright,
        
        // 系统行为
        'behavior.autoSave': basicSettings.systemBehavior.autoSave.toString(),
        'behavior.autoRefresh': basicSettings.systemBehavior.autoRefresh.toString(),
        'behavior.refreshInterval': basicSettings.systemBehavior.refreshInterval.toString(),
        'behavior.theme': basicSettings.systemBehavior.theme,
        
        // 密码策略
        'password.minLength': securitySettings.passwordPolicy.minLength.toString(),
        'password.requireNumber': securitySettings.passwordPolicy.requireNumber.toString(),
        'password.requireSpecialChar': securitySettings.passwordPolicy.requireSpecialChar.toString(),
        'password.requireUppercase': securitySettings.passwordPolicy.requireUppercase.toString(),
        'password.expireDays': securitySettings.passwordPolicy.expireDays.toString(),
        
        // 登录安全
        'login.maxAttempts': securitySettings.loginSecurity.maxAttempts.toString(),
        'login.lockoutDuration': securitySettings.loginSecurity.lockoutDuration.toString(),
        'login.sessionTimeout': securitySettings.loginSecurity.sessionTimeout.toString(),
        
        // API设置
        'api.timeout': networkSettings.api.timeout.toString(),
        'api.retryCount': networkSettings.api.retryCount.toString(),
        'api.baseUrl': networkSettings.api.baseUrl,
        
        // 代理设置
        'proxy.enabled': networkSettings.proxy.enabled.toString(),
        'proxy.host': networkSettings.proxy.host,
        'proxy.port': networkSettings.proxy.port.toString()
      }
      
      await systemApi.updateSystemSettings(settingsData)
      ElMessage.success('设置保存成功')
      return true
    } catch (error: any) {
      ElMessage.error('保存失败: ' + (error.message || '未知错误'))
      throw error
    } finally {
      saving.value = false
    }
  }
  
  // 重置为默认设置
  const resetToDefault = async () => {
    try {
      // 重置为默认值
      Object.assign(basicSettings, {
        systemInfo: {
          name: '小采灵犀智能对账系统',
          description: '基于AI技术的智能对账平台',
          version: 'v1.0.0',
          copyright: '© 2023 小采科技有限公司'
        },
        systemBehavior: {
          autoSave: true,
          autoRefresh: false,
          refreshInterval: 60,
          theme: 'light'
        }
      })
      
      Object.assign(securitySettings, {
        passwordPolicy: {
          minLength: 8,
          requireNumber: true,
          requireSpecialChar: true,
          requireUppercase: true,
          expireDays: 90
        },
        loginSecurity: {
          maxAttempts: 5,
          lockoutDuration: 30,
          sessionTimeout: 120
        }
      })
      
      Object.assign(networkSettings, {
        api: {
          timeout: 10000,
          retryCount: 3,
          baseUrl: 'https://api.example.com'
        },
        proxy: {
          enabled: false,
          host: '',
          port: 8080
        }
      })
      
      ElMessage.success('已恢复默认设置')
      return true
    } catch (error: any) {
      ElMessage.error('操作失败: ' + (error.message || '未知错误'))
      throw error
    }
  }
  
  return {
    // 数据
    loading,
    saving,
    settings,
    basicSettings,
    securitySettings,
    networkSettings,
    
    // 方法
    loadSettings,
    saveSettings,
    resetToDefault
  }
}